package date;

import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by admin on 2017/11/8.
 */
public class WeekTest {
    /**
     * 得到某一天是这一年的第几周
     *
     * @param date
     * @return
     */
    public static int getWeek(String date) {
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            cal.setTime(format.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int week = cal.get(Calendar.WEEK_OF_YEAR);
        System.out.println("==="+cal.getWeekYear());
        return week;
    }

    public static Date getWeekStartDate(){
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY); //设置一周的第一天是周一
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date date = cal.getTime();
        return date;
    }

    public static Date getWeekEndDate(){
        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY); //设置一周的第一天是周一
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        Date date = cal.getTime();
        return date;
    }

    public static void main(String[] args) {
        System.out.println(getWeek("2016-12-30"));
//        System.out.println(getWeek("2017-01-02"));
//        System.out.println(getWeek("2018-12-31"));
//        System.out.println(getWeekStartDate());
//        System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(getWeekEndDate()));
//        System.out.println(Calendar.getInstance().get(Calendar.WEEK_OF_YEAR));
//        System.out.println(Calendar.getInstance().getWeekYear());
    }

    @Test
    public void test01(){
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.add(Calendar.DATE,-7);
        System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));
    }

}
